﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Aksesuar
{
    
    public partial class AksesuarSec : XForm
    { 
        public class Category
        {
            public bool Visible { get; set; }
           

            public Category()
            {
                // TODO: Complete member initialization
            }
            public int ProductCategoryId { get; set; }
            public int Number { get; set; }
            public string Name { get; set; }
           

            //public void Swap(Category DestCategory)
            //{
            //    Category TempCategory = new Category(this.PictureEdit, this.Label);
            //    TempCategory.ProductCategoryId = this.ProductCategoryId;
            //    TempCategory.Number = this.Number;
            //    TempCategory.Name = this.Name;
            //    TempCategory.Visible = this.Visible;

            //    this.ProductCategoryId = DestCategory.ProductCategoryId;
            //    this.Number = DestCategory.Number;
            //    this.Name = DestCategory.Name;
            //    this.Visible = DestCategory.Visible;
            //    this.PictureEdit = DestCategory.PictureEdit;
            //    this.Label = DestCategory.Label;

            //    DestCategory.ProductCategoryId = TempCategory.ProductCategoryId;
            //    DestCategory.Number = TempCategory.Number;
            //    DestCategory.Name = TempCategory.Name;
            //    DestCategory.Visible = TempCategory.Visible;
            //    DestCategory.PictureEdit = TempCategory.PictureEdit;
            //    DestCategory.Label = TempCategory.Label;
            //}

            public Image Photo { get; set; }
        }

        List<Category> listCategory = new List<Category>();
        public DataTable DtAksesuar { get; set; }
        public DataRow[] drsSecilmis { get; set; }

        public AksesuarSec()
        {
            InitializeComponent();
            splitContainerControl1.Collapsed = true;
        }
        public AksesuarSec(DataRow[] drAksesuar):this()
        {
            this.drsSecilmis = drAksesuar;
            splitContainerControl1.Collapsed = false;
        }

     
        List<int> seciliPCId = new List<int>();

        DataTable dtZorunlu = null;

        private void AksesuarSec_Load(object sender, EventArgs e)
        {
            gvAksesuar.Init("GetAksesuarforBOM", WhoAmI);

            gvAksesuar.AddColumn("Adet", typeof(decimal));

            gvAksesuar.FormatAsNumber(0, "RaftakiMiktar");
            gvAksesuar.Columns["Adet"].DisplayFormat.FormatString = "#,##0.###";

            gvAksesuar.Columns["AksesuarId"].ColumnEdit = new RepositoryItemTextEdit();
            gvAksesuar.Columns["AksesuarId"].OptionsColumn.AllowEdit = false;
            gvAksesuar.Columns["AksesuarId"].AppearanceCell.BackColor = System.Drawing.Color.LightYellow;

            GridManager gm = gvAksesuar.GetManager();

            splitContainerControl1.Panel2.AutoScroll = true;

            DataTable dtTumAks = gvAksesuar.DataTable();
            if(drsSecilmis!=null)
            {
                dtZorunlu = gvAksesuar.Dataset().Tables[1];
                
                foreach (DataRow drSecilmis in drsSecilmis)
                {
                    int sAksesuarId = drSecilmis["AksesuarId"].ToInt();
                    if (sAksesuarId > 0)
                    {
                        int sProductCategoryId = AppSession.Lookups.V_Aksesuar.FindByAksesuarId(sAksesuarId).ProductCategoryId;
                        decimal sQty = drSecilmis["Qty"].ToDecimal();
                        dtTumAks.Select("AksesuarId=" + sAksesuarId)[0]["Adet"] = sQty;
                        seciliPCId.Add(sProductCategoryId);
                    }
                }

                for (int i = 0; i < dtZorunlu.Rows.Count; i++)
                {

                    DataRow drZorunlu = dtZorunlu.Rows[i];
                    int ProductCategoryId = drZorunlu["ProductCategoryId"].ToInt();
                    string Category = drZorunlu["Name"].ToStr();

                    Category category = new Category();
                    category.ProductCategoryId = ProductCategoryId;
                    category.Photo = GetPhoto(i);
                    category.Number = i;
                    category.Name = Category;

                    category.Visible = !seciliPCId.Contains(ProductCategoryId);
                    listCategory.Add(category);
                }

                RefresfBoxes();
            }
            gvAksesuar.Columns["Adet"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
            gvAksesuar.Columns["AksesuarId"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            riQty = new RepositoryItemTextEdit();
            riQty.Mask.EditMask = "[2,4]";
            riQty.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;

            emptyEditor = new RepositoryItemButtonEdit();
            emptyEditor.Buttons.Clear();
            emptyEditor.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            gcAksesuar.RepositoryItems.Add(emptyEditor);

            bbiEkle.ItemClick += bbiEkle_ItemClick;
            gvAksesuar.CustomRowCellEdit += gvAksesuar_CustomRowCellEdit;
            gvAksesuar.ShowingEditor += gvAksesuar_ShowingEditor;
            gvAksesuar.RowCellStyle += gvAksesuar_RowCellStyle;
            gvAksesuar.CellValueChanged += gvAksesuar_CellValueChanged;
            splitContainerControl1.Panel2.SizeChanged += splitContainerControl1_SizeChanged;
            gm.Pasting += gm_Pasting;

            gvAksesuar.BestFitColumns();
            gvAksesuar.AddSummary();

            gvAksesuar.FocusedRowHandle = 0;
        }

        void gm_Pasting(int rowHandle, DevExpress.XtraGrid.Columns.GridColumn column, object val, CancelEventArgs ce)
        {
            if (rowHandle < 0)
                return;
            if (column.FieldName == "Adet" && val.ToStr() != "")
            {
                DataTable dtZorunluAdet = gvAksesuar.Dataset().Tables[2];
                int ProductCategoryId = gvAksesuar.GetRowCellValue(rowHandle, "ProductCategoryId").ToInt();
                int AksesuarId = gvAksesuar.GetRowCellValue(rowHandle, "AksesuarId").ToInt();

                bool IsProductCategoryExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId).Length > 0;
                bool IsOptionExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId + " and Isnull(Qty,0) = " + val.ToStr().Replace(",", ".")).Length > 0;

                ce.Cancel = (IsProductCategoryExist && !IsOptionExist) || AksesuarId == 0;
            }
        }

        RepositoryItemTextEdit riQty;
        void gvAksesuar_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;

            int AksesuarId = view.GetRowCellValue(view.FocusedRowHandle, "AksesuarId").ToInt();
            e.Cancel = view.FocusedColumn.FieldName == "Qty" && AksesuarId == 0;
        }

        RepositoryItemButtonEdit emptyEditor;
        void gvAksesuar_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.Column.FieldName == "Seri" &&
                view.GetRowCellDisplayText(e.RowHandle, "AksSeriId") == string.Empty)
                e.RepositoryItem = emptyEditor;

            else if (e.Column.FieldName == "Adet")
            {
                DataTable dtZorunluAdet = view.Dataset().Tables[2];
                int ProductCategoryId = view.GetRowCellValue(e.RowHandle, "ProductCategoryId").ToInt();
                bool IsProductCategoryExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId).Length > 0;
                if (IsProductCategoryExist)
                {
                    List<string> adet = new List<string>();
                    foreach (DataRow dr in dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId))
                        adet.Add(dr["Qty"].ToDecimal().ToString("#,##0.###"));

                    RepositoryItemComboBox riAdet = new RepositoryItemComboBox();
                    riAdet.Items.AddRange(adet);
                    riAdet.TextEditStyle = TextEditStyles.DisableTextEditor;
                    e.RepositoryItem = riAdet;
                }
            }
        }

        void splitContainerControl1_SizeChanged(object sender, EventArgs e)
        {
            if(!splitContainerControl1.Collapsed)
            RefresfBoxes();
        }

        private void RefresfBoxes()
        {
            panelControl1.Controls.Clear();

            Label lbBaslik = new Label();
            lbBaslik.Font = new System.Drawing.Font("Calibri", 15F, System.Drawing.FontStyle.Bold);
            lbBaslik.Location = new System.Drawing.Point(1, 5);
            lbBaslik.Size = new Size(223,40);
            lbBaslik.Text = "EksikKategoriler";
            panelControl1.Controls.Add(lbBaslik);

            int boxIndex = 0;
            for (int i = 0; i < listCategory.Count; i++)
            {
                Category cat = listCategory[i];
                cat.Visible = !seciliPCId.Contains(cat.ProductCategoryId);

                if (cat.Visible)
                {
                    PictureEdit pe = new PictureEdit();
                    pe.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch;

                    Label lbl = new Label();

                    panelControl1.Controls.Add(pe);
                    panelControl1.Controls.Add(lbl);

                    pe.Image = cat.Photo;
                    int row = splitContainerControl1.Panel2.Width / 110;
                    int heigh = 84;
                    int width = 110;
                    int x = (boxIndex * width) % (row * width);
                    int y = ((boxIndex) / row) * (heigh + (lbl.Height * 2)) + 50;
                    pe.Location = new Point(x, y);

                    lbl.Text = cat.Name;
                    lbl.Location = new Point(x + 1, y + 84 + lbl.Height);
                    boxIndex++;
                }
            }
        }



        void gvAksesuar_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            DataRow dr = gvAksesuar.GetDataRow(e.RowHandle);
            decimal qty = dr["Adet"].ToDecimal();
            int pcId = dr["ProductCategoryId"].ToInt();
            if (qty > 0 && !seciliPCId.Contains(pcId))
                seciliPCId.Add(pcId);
            else if (qty <= 0 && seciliPCId.Contains(pcId))
                seciliPCId.Remove(pcId);

            RefresfBoxes();
        }
        Image GetPhoto(int i)
        {
            DataTable dt = gvAksesuar.Dataset().Tables[1];
            if (dt.Rows[i]["Photo2"] != DBNull.Value)
                return Image.FromStream(new MemoryStream((byte[])dt.Rows[i]["Photo2"]));
            else
                return null;
        }
        void gvAksesuar_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Adet" )
                {
                    if (!gvAksesuar.IsCellSelected(e.RowHandle, e.Column))
                        e.Appearance.BackColor = Color.LightYellow;

                    decimal Qty = gvAksesuar.GetRowCellValue(e.RowHandle, "Adet").ToDecimal();
                    if (Qty > 0)
                        e.Appearance.BackColor = Color.SkyBlue;
                }

            }
        }

        
        void bbiEkle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvAksesuar.EndEditing();
            DataRow[] drAksesuar = gvAksesuar.DataTable().Select("Adet > 0");

            if (drAksesuar.Length == 0)
            {
                ShowErrorMessage("Eklemek istediğiniz aksesuarların adet alanlarını doldurun");
                return;
            }

            DtAksesuar = drAksesuar.CopyToDataTable();
            this.DialogResult = DialogResult.OK;
        }

    }
}
